<template>
  <div class="goods">
    <!-- 图片管理 -->
    <!-- 搜索框 -->
    <div class="search">
      <div class="box1">
        商品名
        <el-input v-model="page.name" placeholder="请输入商品名" maxlength="11" clearable></el-input>
      </div>
      <!-- <div class="box2">
        筛选
        <el-cascader ref="cascaderQuery" :options="options" :props="optionProps" clearable @change="selectQuery" placeholder="请选择分类"></el-cascader>
      </div> -->
      <button @click="searchBtn">查询</button>
    </div>
    <!-- 页面内容 -->
    <div class="table">
      <div class="tableTitle">
        <div class="tableTitleName">商品列表</div>
        <div class="tableTitleBtn">
          <button @click="add">新增</button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        border
        :header-cell-style="{
          textAlign: 'center',
          color: '#333',
          fontWeight: '400',
          fontSize: '14px',
          height: '45px',
          padding: '0px',
          margin: '0',
        }"
        style="width: 100%; margin: 0"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="商品名">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column prop="name" label="封面图"
          ><template slot-scope="scope">
            <el-image style="width: 45px; height: 45px" :src="scope.row.imageUrl" fit="contain" :preview-src-list="srcList" @click="preview(scope.row.imageUrl)"></el-image></template
        ></el-table-column>
        <el-table-column label="原价"
          ><template slot-scope="scope">{{ scope.row.originalPrice }}</template></el-table-column
        >
        <el-table-column label="优惠价"
          ><template slot-scope="scope">{{ scope.row.discountPrice }}</template></el-table-column
        >
        <el-table-column label="外链地址"
          ><template slot-scope="scope">{{ scope.row.url }}</template></el-table-column
        >
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <div v-if="scope.row">
              <span class="spanBtn" style="cursor: pointer; margin-right: 10px" @click="edit(scope.row)">编辑</span>

              <span class="spanBtn" style="cursor: pointer; margin-right: 10px" @click="delBtn(scope.row)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="tableData.length !== 0" style="text-align: center" class="pagbox">
        <el-pagination v-model="page" background layout="prev, pager, next" :total="total" :page-size="page.ps" :current-page="page.p" @current-change="handleCurrentChange"> </el-pagination>
      </div>
      <!-- 新增弹层 -->
      <el-dialog width="800px" :show-close="false" :close-on-click-modal="false" :visible.sync="addShowDia" :close-on-press-escape="false" top="7vh">
        <div class="header" v-if="myedit === false">新增商品</div>
        <div class="header" v-if="myedit === true">编辑商品</div>

        <div class="mybody">
          <div class="box1">
            <p>商品名：</p>
            <el-input v-model="myInfo.name" placeholder="请输入商品名（限制24个字符）" maxlength="24" clearable></el-input>
          </div>
          <div class="box1">
            <p>原价：</p>
            <el-input v-model="myInfo.originalPrice" placeholder="请输入原价" maxlength="11" type="number"></el-input>
          </div>
          <div class="box1">
            <p>优惠价：</p>
            <el-input v-model="myInfo.discountPrice" placeholder="请输入优惠价" maxlength="11" type="number"></el-input>
          </div>
          <div class="box1">
            <p>外链地址：</p>
            <el-input v-model="myInfo.url" placeholder="请输入外链地址" clearable></el-input>
          </div>
          <div class="box1">
            <p>封面图：</p>
            <div class="myimage">
              <el-input v-model="myInfo.imageUrl" placeholder="请从案例库选择图片或输入图片地址" clearable></el-input>
              <button @click="imgShow = true">案例库</button>
            </div>
          </div>
        </div>
        <div class="mybtn">
          <div class="btn1" @click="cancel">取消</div>
          <div class="btn2" @click="confirm">确认</div>
        </div>
      </el-dialog>
      <!-- 选择图片弹层 -->
      <el-dialog width="800px" :show-close="false" :close-on-click-modal="false" :visible.sync="imgShow" :close-on-press-escape="false" top="7vh">
        <!-- <div class="header">选择封面</div> -->
        <div class="imgbody">
          <div class="imgsearch">
            <div class="one">
              <span>名称</span>
              <el-input v-model="imgpage.name" placeholder="请输入图片名" clearable></el-input>
            </div>
            <div class="one">
              <span>分类</span>
              <el-cascader ref="cascaderQuery" :options="options" :props="optionProps" clearable @change="selectQuery" placeholder="请选择分类"></el-cascader>
            </div>
            <button @click="searchimg">搜索</button>
          </div>
          <div class="memo">(默认显示50条数据；点击图片即选择封面图；精确获取图片请使用搜索功能)</div>
          <div class="imgarea">
            <div class="myblock" v-for="(item, index) in imgList" :key="index">
              <img :src="item.url" alt="" @click="setUrl(item.url)" />
            </div>
          </div>
        </div>
        <div class="mybtn">
          <div class="btn1" @click="imgShow = false">取消</div>
          <!-- <div class="btn2" @click="confirm">确认</div> -->
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>

export default {
  name: 'goods',

  data() {
    return {
      imgShow: false,
      myedit: false, // 编辑新增状态
      myInfo: {
        name: '',
        originalPrice: null,
        discountPrice: null,
        url: '',
        imageUrl: '',
        id: null
      }, // 表格数据
      addShowDia: false, // 新增弹窗状态
      typeId: null, // 修改图片分类类型Id
      token: sessionStorage.getItem('token'),
      // 图片预览数组
      srcList: [],
      tableData: [], // 渲染列表数据
      tableDataCopy: [], // 修改时的复制列表数据
      delArr: [], // 删除数组
      page: {
        p: 1, // 分页页数
        ps: 8, // 分页条数
        name: '' // 模糊查询商品
      }, // 商品列表传参
      imgpage: {
        p: 1, // 分页页数
        ps: 50, // 分页条数
        type: null, // 图片分类
        name: '' // 模糊查询商品
      }, // 选择图片传参
      imgList: [], // 图片数组
      options: [], // 筛选列表数组
      total: null, // 总条数
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        disabled: 'disabled'
      }

    }
  },
  created() {
    // 获取商品列表
    this.getlist()
    // 获取图片列表
    this.getimglist()
    // 获取筛选列表
    this.getOptions()
  },
  methods: {
    // 获取商品列表
    async getlist() {
      const res = await this.$http.get(`/commodity/page/${this.page.p}/${this.page.ps}`)
      console.log('liebiao', res.data.data)
      if (res.status === 200) {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }
    },
    //
    //
    //
    //
    //
    //
    //
    // 点击预览图片
    preview(val) {
      this.srcList = []
      this.srcList.push(val)
    },
    // 编辑
    async edit(val) {
      console.log('bianji')
      // 获取当前信息
      const res = await this.$http.get(`/commodity/${val.id}`)
      console.log(res)
      if (res.status === 200) {
        this.myInfo = res.data.data
      }
      this.myedit = true
      this.addShowDia = true
    },

    // 新增
    add() {
      console.log('xinzen')
      this.myInfo = {
        name: '',
        originalPrice: null,
        discountPrice: null,
        url: '',
        imageUrl: '',
        id: null
      }
      this.addShowDia = true
      this.myedit = false
    },
    // 取消新增
    cancel() {
      this.addShowDia = false
    },
    confirm() {
      if (!this.myInfo.name) {
        this.$message({
          type: 'warning',
          message: '请完善商品名'
        })
        return
      }

      if (!this.myInfo.originalPrice) {
        this.$message({
          type: 'warning',
          message: '请完善原价'
        })
        return
      }
      if (!this.myInfo.discountPrice) {
        this.$message({
          type: 'warning',
          message: '请完善优惠价'
        })
        return
      }
      if (!this.myInfo.url) {
        this.$message({
          type: 'warning',
          message: '请完善外链地址'
        })
        return
      }
      if (!this.myInfo.imageUrl) {
        this.$message({
          type: 'warning',
          message: '请完善封面图'
        })
        return
      }
      if (this.myedit === true) {
        this.$confirm('确认保存修改', '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.myInfo.originalPrice = Number(this.myInfo.originalPrice)
          this.myInfo.discountPrice = Number(this.myInfo.discountPrice)
          const res = await this.$http.post('/commodity/save', this.myInfo)
          // console.log('删除返回信息', res)
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              type: 'success',
              message: '修改成功'
            })
            this.delArr = []
            this.getlist()
            this.addShowDia = false
          } else {
            this.$message.error('修改失败')
          }
        }).catch(
          () => {
            this.$message({
              showClose: true,
              type: 'info',
              message: '已取消'
            })
          })
      } else {
        this.$confirm('确认保存新增', '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.myInfo.originalPrice = Number(this.myInfo.originalPrice)
          this.myInfo.discountPrice = Number(this.myInfo.discountPrice)
          const res = await this.$http.post('/commodity/save', this.myInfo)
          // console.log('删除返回信息', res)
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              type: 'success',
              message: '新增成功'
            })
            this.delArr = []
            this.getlist()
            this.addShowDia = false
          } else {
            this.$message.error('新增失败')
          }
        }).catch(
          () => {
            this.$message({
              showClose: true,
              type: 'info',
              message: '已取消'
            })
          })
      }
      // this.addShowDia = false
    },

    // 获取图片列表
    async getimglist() {
      const res = await this.$http.get('/image/list', { params: { p: this.imgpage.p, ps: this.imgpage.ps, imageTypeId: this.imgpage.type, name: this.imgpage.name } })
      console.log('图片列表', res)
      if (res.data.code === 200) {
        this.imgList = res.data.data.imageList
        // this.tableDataCopy = JSON.parse(JSON.stringify(res.data.data.imageList))
        // this.total = res.data.data.count
        // this.tableData.forEach(item => {
        //   item.myData = [{ id: null }]
        //   item.myData[0].id = item.imageType.id
        //   console.log(item)
        // })
        console.log(this.tableData)
      }
    },
    // 获取筛选列表
    async getOptions() {
      const res = await this.$http.get('/image/type/list')
      console.log('分类列表', res)
      this.options = res.data.data
      this.options.unshift({
        id: 1,
        name: '全部'
      })
      this.options.forEach(item => {
        if (item.children) {
          item.children.unshift({
            id: 2,
            name: '全部'
          })
          item.children.forEach(itm => {
            if (itm.children) {
              itm.children.unshift({
                id: 3,
                name: '全部'
              })
            }
          })
        }
        // if (item.children.children) {
        //   item.children.children.unshift({
        //     id: 3,
        //     name: '全部'
        //   })
        // }
      })
      // 空数组去掉
      this.options = res.data.data || []

      for (const item of this.options || []) {
        if (!item.children || item.children.length === 0) {
          delete item.children
          // item.disabled = 'disabled'
        } else {
          this.deepArr(item.children)
        }
      }
    },
    // 选择图片
    setUrl(val) {
      console.log('xuanzetupian', val)
      this.myInfo.imageUrl = val
      this.imgShow = false
    },
    searchimg() {
      console.log('搜索', this.imgpage)
      this.getimglist()
    },
    deepArr(data) {
      for (const item of data || []) {
        if (!item.children || item.children.length === 0) {
          delete item.children
        } else {
          this.deepArr(item.children)
        }
      }
    },
    // 翻页
    handleCurrentChange(currentPage) {
      this.page.p = currentPage
      this.getlist()
    },
    // 筛选时的节点信息
    selectQuery() {
      // console.log('筛选节点信息', this.$refs.cascaderQuery.getCheckedNodes()[0].data)
      // console.log('筛选长度', this.$refs.cascaderQuery)
      // if (this.$refs.cascaderQuery.checkedValue.length === 0) {
      //   this.page.type = null
      // } else {
      //   const id = this.$refs.cascaderQuery.getCheckedNodes()[0].data.id
      //   this.page.type = id
      // }
      console.log('筛选长度', this.$refs.cascaderQuery.getCheckedNodes())
      if (this.$refs.cascaderQuery.getCheckedNodes()[0]) {
        if (this.$refs.cascaderQuery.getCheckedNodes()[0].data.id === 1) {
          this.imgpage.type = null
        } else if (this.$refs.cascaderQuery.getCheckedNodes()[0].data.id === 2) {
          this.imgpage.type = this.$refs.cascaderQuery.getCheckedNodes()[0].parent.value
        } else if (this.$refs.cascaderQuery.getCheckedNodes()[0].data.id === 3) {
          this.imgpage.type = this.$refs.cascaderQuery.getCheckedNodes()[0].parent.value
        } else {
          this.imgpage.type = this.$refs.cascaderQuery.getCheckedNodes()[0].data.id
        }
      }
      // if (this.$refs.cascaderQuery.getCheckedNodes()[0]) {
      //   const id = this.$refs.cascaderQuery.getCheckedNodes()[0].data.id
      //   this.page.type = id
      // } else {
      //   this.page.type = null
      // }
      console.log(this.page.type)
    },
    // 清空筛选
    clear() {
      this.$refs.cascaderQuery.checkedValue = ''
      this.$refs.cascaderQuery.$refs.panel.activePath = []
      this.$refs.cascaderQuery.$refs.panel.syncActivePath()
    },
    // 查询按钮
    async searchBtn() {
      console.log('查询')
      const res = await this.$http.get(`/commodity/page/${1}/${this.page.ps}?name=${this.page.name}`)
      console.log('liebiao', res.data.data)
      if (res.status === 200) {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }
    },
    // 图片分类类型修改
    // handleChange(val) {
    //   console.log('类型修改', val)
    //   this.typeId = val[val.length - 1]
    //   this.$forceUpdate()
    //   console.log('反转数组', this.typeId)
    // },
    // 图片修改类型失焦
    async changeType(val) {
      console.log('shijiao ', val)
      const changeRes = {
        id: val.id,
        imageTypeId: this.typeId
      }
      const res = await this.$http.post('/image/update', changeRes)
      console.log(res)
      if (res.data.code === 200) {
        this.$message({
          showClose: true,
          type: 'success',
          message: '修改成功'
        })
        this.showdialog = false
        this.$emit('update')
      } else {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '修改失败'
        })
      }
    },

    // 编辑图片按钮
    editBtn() {
      console.log('编辑')
    }, // 删除按钮
    async delBtn(val) {
      console.log('删除', val.id)
      this.delArr.push(val.id)
      this.$confirm('确认删除这项商品', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$http.delete('/commodity/delete', { data: this.delArr })
        console.log('删除返回信息', res)
        if (res.data.code === 200) {
          this.$message({
            showClose: true,
            type: 'success',
            message: '删除成功'
          })
          this.delArr = []
          this.getlist()
        } else {
          this.$message.error('删除失败')
        }
      }).catch(
        () => {
          this.$message({
            showClose: true,
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 多选图片事件
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log('多选', val)
    }
  }
}
</script>
<style lang="less">
body,
html,
#app {
  min-width: 1100px !important;
}
</style>
<style lang="less" scoped>
.goods {
  padding: 15px 20px;
  .search {
    width: 100%;
    height: 50px;
    display: flex;
    background-color: #fff;
    box-sizing: border-box;
    .box1 {
      font-size: 14px;
      color: #555;
      margin-right: 30px;

      /deep/ .el-input {
        width: 140px;
        height: 30px;
        border-radius: 15px;
        .el-input__inner {
          width: 140px;
          height: 30px;
          border-radius: 15px;
        }
      }
    }
    .box2 {
      font-size: 14px;
      color: #555;
      margin-right: 30px;
      /deep/.el-cascader {
        width: 250px;

        line-height: 30px;
        .el-input .el-input__inner {
          border-radius: 30px !important;
          height: 30px !important;
          line-height: 30px !important;
        }
      }
      .el-select {
        width: 110px;
        height: 30px;
        /deep/ .el-input {
          width: 110px;
          height: 30px;
          line-height: 30px;
          border-radius: 15px;
          .el-input__inner {
            width: 110px;
            height: 30px;
            border-radius: 15px;
          }
        }
      }
    }
    button {
      cursor: pointer;
      box-sizing: border-box;
      font-size: 16px;
      color: #ffffff;
      width: 90px;
      height: 30px;
      background: #333333;
      border-radius: 18px;
    }
  }
  .table {
    background-color: #fff;
    .tableTitle {
      position: relative;
      height: 50px;
      line-height: 50px;
      background-color: #eee;
      .tableTitleName {
        font-size: 16px;
        color: #333;
        margin-left: 20px;
      }
      .tableTitleBtn {
        position: absolute;
        top: 0;
        right: 25px;
        button {
          cursor: pointer;
          width: 80px;
          height: 30px;
          border-radius: 15px;
          font-size: 16px;
          color: #333;
          margin-left: 15px;
        }
        .delBtn {
          width: 105px;
        }
      }
    }
  }
  /deep/ .el-dialog__wrapper {
    .el-dialog {
      width: 800px !important;

      .el-dialog__header {
        display: none;
      }
      .el-dialog__body {
        padding: 0;
        .header {
          width: 100%;
          height: 40px;
          line-height: 40px;
          background-color: #eee;
          font-size: 16px;
          color: #333;
          text-align: center;
          margin-bottom: 30px;
        }
        .imgbody {
          width: 100%;
          .imgsearch {
            width: 80%;
            height: 50px;
            padding-top: 20px;
            margin: 0 auto;
            // margin-left: 30px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            .one {
              width: 200px;
              margin-right: 15px;
              display: flex;
              align-items: center;
              span {
                display: inline-block;
                width: 50px;
              }
            }
            button {
              cursor: pointer;
              box-sizing: border-box;
              font-size: 16px;
              color: #ffffff;
              width: 90px;
              height: 30px;
              background: #333333;
              border-radius: 18px;
              margin-left: 20px;
            }
          }
          .memo {
            width: 80%;
            margin: 0 auto;
            margin-bottom: 10px;
          }
          .imgarea {
            width: 80%;
            max-height: 400px;
            margin: 0 auto;
            overflow: auto;
            display: flex;
            flex-wrap: wrap;
            .myblock {
              width: 100px;
              height: 100px;
              margin-right: 3px;
              margin-bottom: 5px;
              // border: 1px solid #333;
              img {
                width: 100px;
                object-fit: contain;
                cursor: pointer;
              }
            }
          }
        }
        .mybody {
          width: 80%;
          margin: 0 auto;

          .box1 {
            width: 100%;
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            p {
              min-width: 100px;
              text-align: right;
            }
            .myimage {
              flex: 1;
              display: flex;
              button {
                width: 70px;
                height: 20px;
                margin-left: 20px;
                background-color: #fff;
                border-radius: 20px;
                border-color: #555;
                font-size: 12px;
                line-height: 16px;
                color: #555;
                cursor: pointer;
              }
            }
          }
        }
        .mybtn {
          width: 270px;
          height: 80px;
          margin: 0 auto;
          display: flex;
          justify-content: center;
          align-items: center;
          .btn1 {
            width: 100px;
            height: 31px;
            background-color: #fff;
            border: 2px solid #333;
            color: #333;
            font-size: 14px;
            border-radius: 20px;
            margin-right: 70px;
            text-align: center;
            line-height: 31px;
            cursor: pointer;
          }
          .btn2 {
            cursor: pointer;
            width: 100px;
            height: 35px;
            background-color: #333;
            color: #fff;
            font-size: 14px;
            border-radius: 20px;
            text-align: center;
            line-height: 35px;
            cursor: pointer;
          }
        }
      }
    }
  }
  // 清除input数字按钮按钮
  /deep/ input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type='number'] {
    -moz-appearance: textfield;
  }
  // 隐藏上传文件列表
  /deep/.el-upload-list {
    display: none;
  }

  // 修改级联选择器箭头行高
  /deep/.el-input__icon {
    line-height: 30px !important;
  }
  // 翻页按钮样式修改
  .pagbox {
    /deep/.el-pagination.is-background .el-pager li:not(.disabled).active {
      background-color: #333;
    }
  }
  // 修改行高
  /deep/.el-table td {
    padding: 0;
  }
  // 修改图片预览时的关闭按钮颜色和位置
  /deep/.el-image-viewer__wrapper .el-icon-circle-close:before {
    color: #fff;
  }
  /deep/.el-image-viewer__wrapper .el-image-viewer__close {
    top: 10%;
    right: 5%;
  }
}
</style>
